package com.example.ftp.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.io.Util;

import static com.example.ftp.util.FTPClientUtil.*;

public class FTPClientService {
	public int copyFile(Map<String, String> configMap, InputStream fileToCopy, String targetPath) throws IOException{
		int responseCode = 0;
		OutputStream os = null;
		FTPClient ftpClient = null;
		
		if ((configMap != null) && !configMap.isEmpty() && (fileToCopy != null) && StringUtils.isNotBlank(targetPath)){
			
			try {
				
				ftpClient = new FTPClient();
				
				connect(ftpClient, configMap.get("ftp.host"), configMap.get("ftp.port"));
				
				if (ftpClient.login(configMap.get("ftp.userName"), configMap.get("ftp.password"))){
					os = ftpClient.storeFileStream(targetPath);
					
					if (os != null){
						Util.copyStream(fileToCopy, os);
					}
						
				}
				
				responseCode = ftpClient.getReplyCode();
				
			} finally {
				
				try{
					
					if (os != null) {
						os.close();
					}
					
					if (fileToCopy != null){
						fileToCopy.close();
					}
					
					close(ftpClient);
					
					responseCode = (responseCode == 0) ? ftpClient.getReplyCode() : responseCode;
					
				} catch(IOException ioe){
					
				} finally {
					ftpClient = null;
				}
			}
		}
		
		return responseCode;
	}
}